import { getQueryPageApi } from "@/api/approval/approvalManagement/index";
import { getChargeCostByWabbillApi } from "@/api/waybillManagement/businessWaybill/detainDoods";
import { computed, reactive, ref } from "vue";

export default function InitHook(state: any) {
  const { passData } = state;
  const formState = reactive<CustomerServiceWaybill.AddProblemFrom>({
    bizProblemPieceTypeId: undefined,
    totalPrice: 0,
    unitPrice: 0,
    costType: 1,
    description: "",
    costList: [
      {
        id: "",
        bizOrderShipmentCostId: 0,
        costName: "",
        unitPrice: 0,
        number: 0,
        totalPrice: 0
      }
    ]
  });
  const loading = ref<boolean>(false);
  const formDataRef = ref<any>(null);
  const getProblemOptions = ref<Array<CustomerServiceWaybill.AddProblemFrom>>([]); //问题件类型下拉框值

  //分摊个人比例
  const personProportion = ref<number>(0);

  //分摊公司比例
  const companyProportion = ref<number>(0);

  //获取问题件类型
  const getProblemOptionsApi = () => {
    return getQueryPageApi({ pageNum: 1, pageSize: 100, total: 100 }).then(({ data: { records } }: any) => {
      getProblemOptions.value = records.map((t: any) => {
        return { label: t.type, value: t.id, ...t };
      });
    });
  };
  //获取附加费
  const getChargeCostByWabbillHandle = () => {
    const params = {
      shipmentId: passData.value.id,
      typeList: [2, 3]
    };
    return getChargeCostByWabbillApi(params).then(({ data }: any) => {
      formState.costList = data.map((t: any) => {
        return { costName: t.costName, unitPrice: t.unitPrice, number: t.number, totalPrice: t.totalPrice, id: t.id };
      });
    });
  };

  //精度丢失处理
  const precisionHandle = (number: number) => {
    return Number(((number * 100) / 100).toFixed(2));
  };
  //总金额
  const getAllPrice = computed(() => {
    const { bizProblemPieceTypeId, totalPrice, unitPrice } = formState;
    const { settlementWeight, settlementPrice } = passData.value;

    const allPrice = new Map([
      ["坏账", precisionHandle(totalPrice)],
      ["单价", precisionHandle(unitPrice * Number(settlementWeight))],
      ["重量差", precisionHandle(unitPrice * Number(settlementPrice))],
      ["附加费", formState.costList && precisionHandle(formState.costList.reduce((account: any, newData: any) => newData.unitPrice * newData.number + account, 0))]
    ]);

    return allPrice.get(bizProblemPieceTypeId as string) || 0;
  });

  //个人分摊费用
  const personPrice = computed(() => {
    return precisionHandle(getAllPrice.value * (personProportion.value / 10));
  });

  //公司分摊费用
  const companyPrice = computed(() => {
    return precisionHandle(getAllPrice.value - personPrice.value);
  });
  return {
    formState,
    loading,
    formDataRef,
    getProblemOptions,
    getProblemOptionsApi,
    getAllPrice,
    getChargeCostByWabbillHandle,
    personPrice,
    companyPrice,
    personProportion,
    companyProportion
  };
}
